import { defineStore } from 'pinia';
import { MEMBER_KEY, ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY } from '@/config';
import { login, loginWx, member } from '@/api';
import type { LoginForm } from '@/types';

export default defineStore('app', {
	state: () => {
		return {
			currentTab: 0,
			access_token: uni.getStorageSync(ACCESS_TOKEN_KEY) || '',
			refresh_token: uni.getStorageSync(REFRESH_TOKEN_KEY) || '',
			member: uni.getStorageSync(MEMBER_KEY) || null
		};
	},
	actions: {
		login(loginFrom: LoginForm) {
			return new Promise(async (resolve, reject) => {
				try {
					const res: any = await login(loginFrom);
					this.access_token = res.data.access_token;
					this.refresh_token = res.data.refresh_token;
					uni.setStorageSync(ACCESS_TOKEN_KEY, res.data.access_token);
					uni.setStorageSync(REFRESH_TOKEN_KEY, res.data.refresh_token);
					resolve(res);
				} catch (error) {
					//TODO handle the exception
					reject(error);
				}
			});
		},
		loginWx() {
			return new Promise(async (resolve, reject) => {
				try {
					const { code } = await uni.login({ provider: 'weixin' });
					const res: any = await loginWx(code);
					this.access_token = res.data.access_token;
					this.refresh_token = res.data.refresh_token;
					uni.setStorageSync(ACCESS_TOKEN_KEY, res.data.access_token);
					uni.setStorageSync(REFRESH_TOKEN_KEY, res.data.refresh_token);
					resolve(res);
				} catch (error) {
					//TODO handle the exception
					reject(error);
				}
			});
		},

		info() {
			return new Promise(async (resolve, reject) => {
				try {
					const res: any = await member();
					this.member = res.data;
					uni.setStorageSync(MEMBER_KEY, res.data);
					resolve(res);
				} catch (error) {
					//TODO handle the exception
					reject(error);
				}
			});
		},
		logout() {
			this.access_token = '';
			this.refresh_token = '';
			this.member = null;
			uni.setStorageSync(ACCESS_TOKEN_KEY, '');
			uni.setStorageSync(REFRESH_TOKEN_KEY, '');
			uni.setStorageSync(MEMBER_KEY, '');
		}
	}
});
